package com.yyz.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyz.lease.common.exception.LeaseException;
import com.yyz.lease.common.result.ResultCodeEnum;
import com.yyz.lease.model.entity.*;
import com.yyz.lease.model.enums.ItemType;
import com.yyz.lease.web.admin.mapper.*;
import com.yyz.lease.web.admin.service.*;
import com.yyz.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.yyz.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.yyz.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.yyz.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.yyz.lease.web.admin.vo.fee.FeeValueVo;
import com.yyz.lease.web.admin.vo.graph.GraphVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 */
@Service
@RequiredArgsConstructor
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    private final GraphInfoService graphInfoService;
    private final ApartmentLabelService apartmentLabelService;
    private final ApartmentFeeValueService apartmentFeeValueService;
    private final ApartmentFacilityService apartmentFacilityService;

    private final ApartmentInfoMapper apartmentInfoMapper;
    private final GraphInfoMapper graphInfoMapper;
    private final FacilityInfoMapper facilityInfoMapper;
    private final LabelInfoMapper labelInfoMapper;
    private final FeeValueMapper feeValueMapper;
    private final RoomInfoMapper roomInfoMapper;
    private final DistrictInfoService districtInfoService;
    private final CityInfoService cityInfoService;
    private final ProvinceInfoService provinceInfoService;


    /**
     * 保存或更新公寓信息
     */
    @Override
    @Transactional
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //判断是否为修改
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        if (apartmentSubmitVo.getDistrictName() == null || apartmentSubmitVo.getDistrictName().equals("")) {
            apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());
        }
        if (apartmentSubmitVo.getCityName() == null || apartmentSubmitVo.getCityName().equals("")) {
            apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        }
        if (apartmentSubmitVo.getProvinceName() == null || apartmentSubmitVo.getProvinceName().equals("")) {
            apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        }
        this.saveOrUpdate(apartmentSubmitVo);

        if (isUpdate) {
            //修改操作
            //1.删除图片
            LambdaQueryWrapper<GraphInfo> graphInfoQuery = new LambdaQueryWrapper<>();
            graphInfoQuery.eq(GraphInfo::getItemType, ItemType.APARTMENT)
                    .eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphInfoService.remove(graphInfoQuery);

            //2.删除标签
            LambdaQueryWrapper<ApartmentLabel> labelInfoQueryWrapper = new LambdaQueryWrapper<>();
            labelInfoQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(labelInfoQueryWrapper);

            //3.删除杂费
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeQueryWrapper);

            //4.删除配套
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityQueryWrapper);
        }

        //插入图片
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (graphVoList != null) {
            List<GraphInfo> graphInfos = graphVoList.stream()
                    .map(graphVo -> {
                        GraphInfo graphInfo = new GraphInfo();
                        graphInfo.setName(graphVo.getName());
                        graphInfo.setUrl(graphVo.getUrl());
                        graphInfo.setItemType(ItemType.APARTMENT);
                        graphInfo.setItemId(apartmentSubmitVo.getId());
                        return graphInfo;
                    }).toList();
            graphInfoService.saveBatch(graphInfos);
        }


        //插入标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (labelIds != null) {
            List<ApartmentLabel> apartmentLabels = labelIds.stream()
                    .map(id -> ApartmentLabel.builder()
                            .apartmentId(apartmentSubmitVo.getId())
                            .labelId(id).build())
                    .toList();
            apartmentLabelService.saveBatch(apartmentLabels);
        }


        //插入杂费
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (facilityInfoIds != null) {
            List<ApartmentFacility> apartmentFacilities = facilityInfoIds.stream()
                    .map(id -> ApartmentFacility.builder()
                            .apartmentId(apartmentSubmitVo.getId())
                            .facilityId(id).build())
                    .toList();
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }


        //插入配套
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (feeValueIds != null) {
            List<ApartmentFeeValue> apartmentFeeValues = feeValueIds.stream()
                    .map(id -> ApartmentFeeValue.builder()
                            .apartmentId(apartmentSubmitVo.getId())
                            .feeValueId(id).build())
                    .toList();
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }

    }

    /**
     * 分页查询公寓信息
     */
    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageApartmentItemByQuery(page, queryVo);
    }

    /**
     * 根据id查询公寓信息
     */
    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        //查询公寓信息
        ApartmentInfo apartmentInfo = this.getById(id);

        //查询图片信息
        List<GraphVo> graphVoList = graphInfoMapper.getGraphInfoByItemTypeAndItemId(ItemType.APARTMENT, id);

        //查询配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.getFacilityInfoByApartmentId(id);

        //查询标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.getLabelInfoByApartmentId(id);

        //查询杂费信息
        List<FeeValueVo> feeValueVoList = feeValueMapper.getFeeValueVosByApartmentId(id);

        //封装信息
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return apartmentDetailVo;
    }

    @Override
    @Transactional
    public void removeApartmentById(Long id) {
        //判断该公寓下是否有房间
        LambdaQueryWrapper<RoomInfo> roomInfoQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomInfoQueryWrapper);
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.ADMIN_APARTMENT_DELETE_ERROR);
        }

        //删除公寓信息
        this.removeById(id);

        //1.删除图片
        LambdaQueryWrapper<GraphInfo> graphInfoQuery = new LambdaQueryWrapper<>();
        graphInfoQuery.eq(GraphInfo::getItemType, ItemType.APARTMENT)
                .eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphInfoQuery);

        //2.删除标签
        LambdaQueryWrapper<ApartmentLabel> labelInfoQueryWrapper = new LambdaQueryWrapper<>();
        labelInfoQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelInfoQueryWrapper);

        //3.删除杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(apartmentFeeQueryWrapper);

        //4.删除配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(apartmentFacilityQueryWrapper);
    }
}




